<?php
header( 'Content-Type: application/json');
session_start();
require_once('../../lib/JSON.php');
require_once('../../config/connection.php');
require_once('../../utils/CommonUtils.php');
require_once('../../utils/DBUtils.php');
require_once('../../utils/Constants.php');
require_once('../../utils/Uploader.php');
require_once('../../application/model/BaseDAO.php');
require_once("../../lib/core/Session.php");
require_once("../../lib/core/Object.php");
require_once("../../application/model/UserMenuDAO.php");
require_once('../../utils/Resources.php');
$commonUtils = new CommonUtils();
$baseDAO = new BaseDAO();
$usermenuDAO = new UserMenuDAO();

$returnRes = array();
$page = $commonUtils->getParameter("page");
if (!isset($page) || $page == '') {
	$page = "list";
}

$action = $commonUtils->getParameter("crudaction");
$sortDirection = $commonUtils->getParameter("dir", "DESC");

$id = $commonUtils->getParameter("id");
$username = $commonUtils->getParameter("username");
$fullname = $commonUtils->getParameter("fullname");
$email = $commonUtils->getParameter("email");
$password =  $commonUtils->getParameter("password");
$address =  $commonUtils->getParameter("address");
$active = $commonUtils->getParameter("active");
$roles = $commonUtils->getParameter("roles");
$createddate = $commonUtils->getDate();
$updateddate = $commonUtils->getDate();
$createdby = Session::get('userid');
$updatedby = Session::get('userid');

if ($page == "list") {
	$sortExpression = $commonUtils->getParameter("sort", "id");
	$begin = $commonUtils->getParameter("pg4_offset", 0);
	$limit = $commonUtils->getParameter("maxPageItems", 10);
	
	if (isset($action) && $action  == 'delete') {
		$checkList = $commonUtils->getParameter("checkList");
		if (isset($action) && $action  == 'delete') {
			$checkList = $commonUtils->getParameter("checkList");
			$ids = explode("|", $checkList);
			$returnRes['ids'] = $ids;
			if (isset($ids) && is_array($ids)) {
				foreach($ids as $id) {
					$curr_user = $baseDAO->getItem("user", array("username"), $id);
					if (isset($curr_user) && is_array($curr_user)) {
						if ($curr_user["username"] != 'admin') {
							$baseDAO->del("user", $id);
							$baseDAO->del("user_menu", $id, "userid");
						}
					}
				}	
			}
		}
	}
	
	$query = " 1 = 1";
	if (isset($fullname) && $fullname != '') {
		$query .= " AND fullname LIKE '%" . $fullname . "%'";
	}
	
	if (isset($email) && $email != '') {
		$query .= " AND email LIKE '%" . $email . "%'";
	}
	
	if (isset($username) && $username != '') {
		$query .= " AND username LIKE '%" . $username . "%'";
	}
	
	if (isset($active) && $active != '') {
		$query .= " AND active = " . $active;
	}
	if (isset($sortExpression) && $sortExpression != '') {
		$orderby = " ORDER BY $sortExpression $sortDirection";
	}
	$query .= " AND username <> 'admin'"; //not show user admin
	
	$items = $baseDAO->getItems("user", array("id", "username", "fullname", "email", "address", "active", "updateddate", "updatedby"), $query, $orderby, $begin, $limit);
	$totalItems = $baseDAO->getTotalItems("user", $query);
	$returnRes['listResult'] = $items;
	$returnRes['totalItems'] = $totalItems;
	$returnRes['data'] = array('crudaction' => 'search');
	
}else if ($page == "edit") {
	if (isset($action) && $action == 'insert-update') {
		if (isset($id) && $id > 0) {
			$values = array($id, $username, $fullname, $email, $address, $active, $updateddate, $updatedby);
			$res = $baseDAO->update("user", array("id", "username", "fullname", "email", "address", "active", "updateddate", "updatedby"), $values);
			if (isset($res) && $res >= 1) {
				// add to role table.
				$baseDAO->del("user_menu", $id, "userid");
				$arrRole = explode('|', $roles);
				if(count($arrRole) > 0){
					foreach($arrRole as $item){
						$arrItems = explode('_', $item);
						if(count($arrItems) > 1){
							$roleValue = array($id, $arrItems[0],$arrItems[1]);
							$resRole = $baseDAO->create("user_menu", array("userid", "menuid", "role"), $roleValue);
						}
					}
				}
				// end
				if(isset($resRole) && $resRole >=1) 
					$returnRes["messageResponse"] = $Resources["updatesuccessful"];
			}else{
				$returnRes["messageResponse"] = $Resources["updatefailure"];
			}
		}else{
			$encPwd = sha1($password);
			$values = array($username, $fullname, $email, $encPwd, $address, $active, 0, $createddate, $updateddate, $createdby, $updatedby);
			
			$checkDoublicate = $baseDAO->getItem("user", array("username"), $username,"username");
			if($checkDoublicate["username"] != NULL){
				$returnRes["messageResponse"] = $Resources["usernamedublicate"];
			}else{
				$res = $baseDAO->create("user", array("username", "fullname", "email", "password", "address", "active", "type", "createddate", "updateddate", "createdby", "updatedby"), $values);
				if (isset($res) && $res >= 1) {
					// add to role table.
					$newuser = $baseDAO->getItem("user", array("id"), $username, "username");
					$userId = $newuser['id'];
					$baseDAO->del("user_menu", $userId, "userid");
					$arrRole = explode('|', $roles);
					if(count($arrRole)> 0){
						foreach($arrRole as $item){
							$arrItems = explode('_', $item);
							if(count($arrItems) > 1){
								$roleValue = array($userId, $arrItems[0], $arrItems[1]);
								$resRole = $baseDAO->create("user_menu", array("userid", "menuid", "role"), $roleValue);	
							}
						}
					}
					// end
					if(isset($res) && $res >=1) 
						$returnRes["messageResponse"] = $Resources["addsuccessful"];
				}else{
					$returnRes["messageResponse"] = $Resources["addfailure"];
				}
			}
		}
	}
	$item = $baseDAO->getItem("user", array("id", "username", "fullname", "email", "address", "active", "password", "updateddate", "createdby"), $id);
	$returnRes['data'] = $item;
	//load role
	$menus = $usermenuDAO->loadMenuUser($id);
	$returnRes['Menus'] = $menus;
	//end load role
	
	//get user list
	$query = " 1 = 1";
	
	$sortExpression = $commonUtils->getParameter("sort", "id");
	$begin = $commonUtils->getParameter("pg4_offset", 0);
	$limit = $commonUtils->getParameter("maxPageItems", 10);
	if (isset($sortExpression) && $sortExpression != '') {
			$orderby = " ORDER BY $sortExpression $sortDirection";
	}
	$query .= " AND username <> 'admin'"; //not show user admin
	$items = $baseDAO->getItems("user", array("id", "username", "fullname", "email", "address", "active", "updateddate", "createdby"), $query, $orderby, $begin, $limit);
	$totalItems = $baseDAO->getTotalItems("user", $query);
	$returnRes['listResult'] = $items;
	$returnRes['totalItems'] = $totalItems;
	// edn
}else if ($page == "profile") {
	$id = Session::get("userid");
	if (isset($action) && $action == 'insert-update') {
		$values = array($id, $fullname, $email, $address);
			
		$res = $baseDAO->update("user", array("id", "fullname", "email", "address"), $values);
		if (isset($res) && $res >= 1) {
			$returnRes["messageResponse"] = $Resources["updatesuccessful"];
		}else{
			$returnRes["messageResponse"] = $Resources["updatefailure"];
		}
	}
	$item = $baseDAO->getItem("user", array("id", "fullname", "email", "address"), $id);
	$returnRes['data'] = $item;
}else if ($page == "password") {
	$id = Session::get("userid");
	if (isset($action) && $action == 'insert-update') {
		
		$oldPwd = $commonUtils->getParameter("oldPassword");
		$item = $baseDAO->getItem("user", array("id", "password"), $id);
		if (isset($item) && is_array($item) && $item["password"] == sha1($oldPwd)) {
			$encPwd = sha1($password);
			$values = array($id, $encPwd);
			$res = $baseDAO->update("user", array("id", "password"), $values);
			if (isset($res) && $res >= 1) {
				$returnRes["messageResponse"] = "Mật khẩu của bạn đã được thay đổi thành công. Mật khẩu mới '" . $password . "'";
			}else{
				$returnRes["messageResponse"] = $Resources["updatefailure"];
			}
		}else{
			$returnRes["messageResponse"] = $Resources["passwordnotmatch"];
		}
	}
	$returnRes['data'] = array("id" => $id);
}
$returnRes['success'] = true;
$jsonUtil = new ext_Json();
echo $jsonUtil->encode($returnRes);

?>